package com.lst.tools.wx.smallroutine.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lst.tools.basics.utils.ValidatorUtils;
import com.lst.tools.httpclient.exception.HttpClientException;
import com.lst.tools.httpclient.service.IHttpClientService;
import com.lst.tools.httpclient.vo.HttpClientVo;
import com.lst.tools.wx.smallroutine.constants.WxSmallRoutineEnum;
import com.lst.tools.wx.smallroutine.entity.WxBasicAccessToken;
import com.lst.tools.wx.smallroutine.properties.WxSmallRoutineProperties;
import com.lst.tools.wx.smallroutine.service.IWxSmallRoutineService;
import com.lst.tools.wx.smallroutine.utils.SmallRoutineUtils;
import com.lst.tools.wx.smallroutine.vo.*;
import com.lst.tools.wx.smallroutine.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
@Service
public class WxSmallRoutineService implements IWxSmallRoutineService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxSmallRoutineService.class);

    @Autowired
    private IHttpClientService httpClientService;
    @Autowired
    private WxSmallRoutineProperties wxSmallRoutineProperties;

    @Override
    public SmallRoutineIdVo getOpenIdAndUnionId(SmallRoutineEncryptedDataParam smallRoutineEncryptedDataParam) {
        try {
            ValidatorUtils.validate(smallRoutineEncryptedDataParam);
            String smallRoutineLoginUrl = wxSmallRoutineProperties.getSmallRoutineLoginUrl(smallRoutineEncryptedDataParam);
            HttpClientVo httpClientVo = httpClientService.doPost(smallRoutineLoginUrl);
            if (HttpClientVo.HTTP_OK_STATUS != httpClientVo.getStatus()) {
                LOGGER.error("getOpenIdAndUnionId error!!!  code[{}], content[{}]", httpClientVo.getStatus(), httpClientVo.getContent());
                return null;
            }
            String content = httpClientVo.getContent();
            SmallRoutineIdVo smallRoutineIdVo = JSON.parseObject(content, new TypeReference<SmallRoutineIdVo>() {
            });
            if (!SmallRoutineUtils.checkIdNeed(smallRoutineIdVo)) {
                String dataJson = SmallRoutineUtils.decrypt(smallRoutineIdVo.getSession_key(), smallRoutineEncryptedDataParam.getEncryptedData(), smallRoutineEncryptedDataParam.getIv());
                smallRoutineIdVo = JSON.parseObject(dataJson, new TypeReference<SmallRoutineIdVo>() {
                });
            }
            smallRoutineIdVo.setSession_key(null);
            return smallRoutineIdVo;
        } catch (Exception e) {
            LOGGER.error("getOpenIdAndUnionId error!!!  smallRoutineEncryptedDataParam[{}]", JSON.toJSONString(smallRoutineEncryptedDataParam));
        }
        return null;
    }

    @Override
    public SmallRoutineMobileDataVo getMobileData(SmallRoutineEncryptedDataParam smallRoutineEncryptedDataParam) {
        try {
            ValidatorUtils.validate(smallRoutineEncryptedDataParam);
            String smallRoutineLoginUrl = wxSmallRoutineProperties.getSmallRoutineLoginUrl(smallRoutineEncryptedDataParam);
            HttpClientVo httpClientVo = httpClientService.doPost(smallRoutineLoginUrl);
            if (HttpClientVo.HTTP_OK_STATUS != httpClientVo.getStatus()) {
                LOGGER.error("getMobileData error!!!  code[{}], content[{}]", httpClientVo.getStatus(), httpClientVo.getContent());
                return null;
            }
            String content = httpClientVo.getContent();
            SmallRoutineMobileDataVo smallRoutineMobileDataVo = JSON.parseObject(content, new TypeReference<SmallRoutineMobileDataVo>() {
            });
            String dataJson = SmallRoutineUtils.decrypt(smallRoutineMobileDataVo.getSession_key(), smallRoutineEncryptedDataParam.getEncryptedData(), smallRoutineEncryptedDataParam.getIv());
            return JSON.parseObject(dataJson, new TypeReference<SmallRoutineMobileDataVo>() {
            });
        } catch (Exception e) {
            LOGGER.error("getMobileData error!!!  smallRoutineEncryptedDataParam[{}]", JSON.toJSONString(smallRoutineEncryptedDataParam));
        }
        return null;
    }

    @Override
    public WxBasicAccessToken getWxBasicAccessToken(WxCatchBasicAccessTokenParam wxCatchBasicAccessTokenParam) {
        try {
            ValidatorUtils.validate(wxCatchBasicAccessTokenParam);
            String catchBasicAccessTokenUrl = wxSmallRoutineProperties.getCatchBasicAccessTokenUrl(wxCatchBasicAccessTokenParam);
            HttpClientVo httpClientVo = httpClientService.doGet(catchBasicAccessTokenUrl);
            if (HttpClientVo.HTTP_OK_STATUS != httpClientVo.getStatus()) {
                LOGGER.error("getWxBasicAccessToken error!!!  code[{}], content[{}]", httpClientVo.getStatus(), httpClientVo.getContent());
                return null;
            }
            String responseJson = httpClientVo.getContent();
            WxBasicAccessToken wxBasicAccessToken = JSON.parseObject(responseJson, new TypeReference<WxBasicAccessToken>() {
            });
            if (wxBasicAccessToken == null || StringUtils.isBlank(wxBasicAccessToken.getAccess_token())) {
                LOGGER.error("getWxBasicAccessToken error!!!  responseJson[{}]", responseJson);
                throw new HttpClientException("getWxBasicAccessToken error:" + responseJson);
            }
            return wxBasicAccessToken;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public InputStream getSmallRoutineQRCode(String basicAccessToken, SmallRoutineQRCodeParam smallRoutineQRCodeParam) throws IOException {
        String catchSmallRoutineQRCodeUrlUrl = wxSmallRoutineProperties.getCatchSmallRoutineQRCodeUrlUrl(basicAccessToken);
        String param = JSON.toJSONString(smallRoutineQRCodeParam);
        return httpClientService.doPostJsonReturnStream(catchSmallRoutineQRCodeUrlUrl, param);
    }

    @Override
    public boolean sendTemplateMessage(String accessToken, SmallRoutineTemplateMessageParam smallRoutineTemplateMessageParam) {
        try {
            String sendTemplateMessageUrl = wxSmallRoutineProperties.getSendTemplateMessageUrl(accessToken);
            HttpClientVo httpClientVo = httpClientService.doPostJson(sendTemplateMessageUrl, JSON.toJSONString(smallRoutineTemplateMessageParam));
            if (HttpClientVo.HTTP_OK_STATUS != httpClientVo.getStatus()) {
                LOGGER.error("smallRoutine sendTemplateMessage error!!!  code[{}], content[{}]", httpClientVo.getStatus(), httpClientVo.getContent());
                return false;
            }
            SmallRoutineBaseReturn smallRoutineBaseReturn = JSON.parseObject(httpClientVo.getContent(), new TypeReference<SmallRoutineBaseReturn>() {
            });
            if (!WxSmallRoutineEnum.REQUEST_SUCCESS_CODE.getValue().equals(smallRoutineBaseReturn.getErrcode())) {
                LOGGER.error("smallRoutine sendTemplateMessage error!!!  errcode[{}], errmsg[{}]", smallRoutineBaseReturn.getErrcode(), smallRoutineBaseReturn.getErrmsg());
                return false;
            }
            return true;
        } catch (Exception e) {
            LOGGER.error("smallRoutine sendTemplateMessage error!!! ", e);
        }
        return false;
    }
}
